package com.zhongkun.datahome.service.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhongkun.datahome.service.domain.CustomerBase;
import com.zhongkun.datahome.service.domain.CustomerFamily;
import com.zhongkun.datahome.service.domain.CustomerHouse;
import com.zhongkun.datahome.service.mapper.CustomerBaseMapper;
import com.zhongkun.datahome.service.mapper.CustomerHouseMapper;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @Author: lifengsheng
 * @Date: 2025/4/14 17:15
 * @Desc
 */
@Repository
public class CustomerBaseRepository extends ServiceImpl<CustomerBaseMapper, CustomerBase> {
    @Resource
    private CustomerFamilyRepository customerFamilyRepository;

    public long countByTenantUserId(Long tenantUserId) {
        return this.count(new LambdaQueryWrapper<CustomerBase>()
                .eq(CustomerBase::getTenantUserId, tenantUserId));
    }

    public CustomerBase getOwnerByFamilyId(Long familyId) {
        CustomerFamily family = customerFamilyRepository.getById(familyId);
        if (Objects.isNull(family)) {
            return null;
        }

        return this.getById(family.getOwnerCustomerId());
    }

    public List<CustomerBase> getMemberByFamilyId(Long familyId) {

        return this.list(new LambdaQueryWrapper<CustomerBase>()
                .eq(CustomerBase::getFamilyId, familyId));
    }

    public List<CustomerBase> getMemberByTenantUserId(Long tenantUserId) {
        CustomerBase customerBase = getByTenantUserId(tenantUserId);
        if (Objects.isNull(customerBase)) {
            return Collections.emptyList();
        }

        return getMemberByFamilyId(customerBase.getFamilyId());
    }

    public CustomerBase getByMobile(String mobile) {
        return this.getOne(new LambdaQueryWrapper<CustomerBase>()
                .eq(CustomerBase::getMobile, mobile), false);
    }

    public CustomerBase getByTenantUserId(Long tenantUserId) {
        return this.getOne(new LambdaQueryWrapper<CustomerBase>()
                .eq(CustomerBase::getTenantUserId, tenantUserId), false);
    }
}
